import Mock from 'mockjs';

const Random = Mock.Random;

// 模拟数据库
let users = Array.from({ length: 100 }, (_, index) => ({
  id: index + 1,
  username: Random.name(),
  email: Random.email(),
  phone: /^1[3-9]\d{9}$/,
  role: Random.pick(['admin', 'editor', 'user']),
  status: Random.pick(['active', 'inactive']),
  avatar: Random.image('100x100'),
  createTime: Random.datetime(),
}));

Mock.setup({
  timeout: '300-600'
});

// 获取用户列表
Mock.mock(/\/api\/users\??.*/, 'get', (options) => {
  const url = new URL(options.url, 'http://localhost');
  const page = parseInt(url.searchParams.get('page')) || 1;
  const pageSize = parseInt(url.searchParams.get('pageSize')) || 10;
  const search = url.searchParams.get('search') || '';

  let filteredUsers = users;
  if (search) {
    filteredUsers = users.filter(user => 
      user.username.toLowerCase().includes(search.toLowerCase()) ||
      user.email.toLowerCase().includes(search.toLowerCase()) ||
      user.phone.includes(search)
    );
  }

  const startIndex = (page - 1) * pageSize;
  const endIndex = startIndex + pageSize;
  const paginatedUsers = filteredUsers.slice(startIndex, endIndex);

  return {
    code: 200,
    data: paginatedUsers,
    total: filteredUsers.length,
    message: '获取成功'
  };
});

// 创建用户
Mock.mock('/api/users', 'post', (options) => {
  const body = JSON.parse(options.body);
  const newUser = {
    id: users.length + 1,
    ...body,
    avatar: Random.image('100x100'),
    status: 'active',
    createTime: Random.datetime(),
  };
  users.unshift(newUser); // 将新用户添加到数组开头

  return {
    code: 200,
    data: newUser,
    message: '创建成功'
  };
});

// 更新用户
Mock.mock(/\/api\/users\/\d+/, 'put', (options) => {
  const id = parseInt(options.url.match(/\/api\/users\/(\d+)/)[1]);
  const body = JSON.parse(options.body);
  
  const index = users.findIndex(user => user.id === id);
  if (index > -1) {
    users[index] = {
      ...users[index],
      ...body,
      updateTime: Random.datetime(),
    };
    return {
      code: 200,
      data: users[index],
      message: '更新成功'
    };
  }
  return {
    code: 404,
    message: '用户不存在'
  };
});

// 删除用户
Mock.mock(/\/api\/users\/\d+/, 'delete', (options) => {
  const id = parseInt(options.url.match(/\/api\/users\/(\d+)/)[1]);
  const index = users.findIndex(user => user.id === id);
  
  if (index > -1) {
    users.splice(index, 1);
    return {
      code: 200,
      message: '删除成功'
    };
  }
  return {
    code: 404,
    message: '用户不存在'
  };
});

// 登录接口
Mock.mock('/api/login', 'post', (options) => {
  const { username, password } = JSON.parse(options.body);
  console.log('Login attempt:', { username, password }); // 添加日志

  if (username === 'admin' && password === '123456') {
    return {
      code: 200,
      data: {
        token: Random.string(64),
        user: {
          id: 1,
          username: 'admin',
          avatar: Random.image('100x100'),
          roles: ['admin'],
          permissions: ['*']
        }
      },
      message: '登录成功'
    };
  }
  return {
    code: 401,
    message: '用户名或密码错误'
  };
});

// 仪表盘数据接口
Mock.mock('/api/dashboard/stats', 'get', () => {
  return {
    code: 200,
    data: {
      counts: {
        userTotal: Random.integer(1000, 9999),
        orderTotal: Random.integer(100, 999),
        productTotal: Random.integer(500, 1999),
        revenue: Random.float(10000, 100000, 2, 2)
      },
      recentOrders: Array.from({ length: 5 }, () => ({
        id: Random.id(),
        orderNo: Random.string('number', 10),
        customer: Random.cname(),
        amount: Random.float(100, 1000, 2, 2),
        status: Random.pick(['pending', 'completed', 'cancelled']),
        createTime: Random.datetime()
      })),
      chartData: Array.from({ length: 12 }, (_, index) => ({
        month: `${index + 1}月`,
        sales: Random.integer(100, 1000),
        visitors: Random.integer(1000, 5000)
      }))
    },
    message: '获取成功'
  };
});
